﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Caliburn.Micro;
using GTServices.Entities;
using GTServices.Model;
using GTServices.WPF.Client.ViewModels;


namespace GTServices.WPF.Client.CoRoutines
{ 
    public class ExportCommand : IResult
    {
        public event EventHandler<ResultCompletionEventArgs> Completed;

        public Type ExportType { get; private set; } 

        public ExportCommand(Type t)
        {
            //type to export. 
            ExportType = t; 

        }

        
        public void Execute(ActionExecutionContext context)
        {
            if (ExportType != null)
            {
                //Get the collection.. 

               IList listOfType =  GTApplication.Instance.DataModel.GetListFor(ExportType);
               if (listOfType != null && listOfType.Count > 0)
               {
                   ListPickerViewModel lpvm = new ListPickerViewModel(listOfType, "Name", "Name", System.Windows.Controls.SelectionMode.Extended);
                   if(GTWindowManager.Instance.ShowDialog(lpvm, 300, 300) == true){
                       EntityCollection ec = new EntityCollection();
                       lpvm.SelectedItems.ForEach(x =>
                       {
                           ec.Entities.Add(x as BaseEntity); 
                       });

                       Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                       sfd.DefaultExt = "*.xml";
                       sfd.Filter = "Xml documents (.xml)|*.xml"; // Filter files by extension 
                       if (sfd.ShowDialog() == true)
                       {
                           try
                           {
                               using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.File.Open(sfd.FileName, System.IO.FileMode.Create)))
                               {
                                   sw.Write(GTApplication.Instance.DataModel.GetEntityAsXml(ec));
                               }
                           }
                           catch (Exception e)
                           {
                               throw e;
                           }
                       }
                   }
               }
            }
        }
    }
}
